package org.openrbac.rbac.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.openrbac.rbac.constant.CommonConstant;
import org.openrbac.rbac.utils.JwtUtil;
import org.openrbac.rbac.utils.RedisUtil;
import org.openrbac.rbac.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author bapie
 */
@Component
@AllArgsConstructor
@Slf4j
//由于过滤链条执行过程中会回弹，继承Filter时会执行2次，继承OncePerRequestFilter时每次请求只执行一次
public class SecurityJwtAuthenticationFilter extends OncePerRequestFilter {
    private JwtUtil jwtUtil;
    private ObjectMapper objectMapper;
    private RedisUtil redisUtil;

    @Autowired
    private AntPathMatcher antPathMatcher;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String request_uri = request.getRequestURI();
        for(String url : CommonConstant.WHITE_KEY){
            if(antPathMatcher.match(url,request_uri)){
                filterChain.doFilter(request, response);
                return;
            }
        }
        String authToken = jwtUtil.extractAuthToken(request);
        if (authToken != null) {
            String username = jwtUtil.getUserNameFromToken(authToken);
            if(!username.isEmpty()){
                request.setAttribute(CommonConstant.USERNAME, username);
            }
            Authentication authentication = (Authentication) redisUtil.hashGet(CommonConstant.TOKEN_KEY, username);
            if (authentication == null) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(objectMapper.writeValueAsString(R.error(CommonConstant.TOKEN_ISNOTEXSIST)));
            } else {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, authentication.getCredentials(), authentication.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request, response);
            }
        } else {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(R.error(CommonConstant.TOKEN_ISNOTEXSIST+"1")));
        }
    }

}
